//
//  ScreenshotViewController.swift
//  MyColorPicker
//
//  Created by 火星人 on 2018/9/19.
//  Copyright © 2018年 火星人. All rights reserved.
//

import Cocoa

class ScreenshotViewController: NSViewController {
    
    @IBOutlet weak var displayView: NSView!
    @IBOutlet weak var imgView: ScreenImageView!
    
    var layerTop: TipLayer!
    var halfW = CGFloat(0)
    var halfW1 = CGFloat(0)
    var bitImg: NSBitmapImageRep?
    var img: NSImage?
    var didPickColor: ((_ color: CGColor?) -> Void)?
    lazy var hexLayer = CATextLayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        weak var wself = self
        
        let s = NSScreen.main
        self.view.frame = s!.frame
        self.img = NSImage(contentsOfFile: tmpFile)
        
        
        NSApp.presentationOptions = [.hideMenuBar, .hideDock]
        
        self.displayView.wantsLayer = true
        self.displayView.frame = CGRect(x: -500, y: 0, width: 110, height: 110)
        self.displayView.layer?.cornerRadius = self.displayView.frame.width * 0.5
        self.displayView.layer?.borderColor = CGColor(red: 0.76, green: 0.77, blue: 0.78, alpha: 1.00)
        self.displayView.layer?.borderWidth = 1
        
        self.imgView.wantsLayer = true
        self.imgView.layer?.backgroundColor = CGColor(red: 0, green: 0, blue: 0, alpha: 0.001)
        
        self.imgView.onMouseMovedHandle = { (event: NSEvent) in
            wself?.showTipWithPosition(event.locationInWindow)
        }
        self.imgView.onMouseDownHandle = {
            (event: NSEvent) in
            wself?.closeTip()
        }
        
        self.displayView.layer?.backgroundColor = CGColor.black
        
        self.halfW = self.displayView.frame.width * 0.5
        
        let layerTop = TipLayer()
        let p = self.displayView.frame.height * 0.1
        let h = self.displayView.frame.height * 0.8
        layerTop.frame = CGRect(origin: CGPoint(x: p, y: p), size: CGSize(width: h, height: h))
        layerTop.cornerRadius = h * 0.5
        layerTop.masksToBounds = true
        
        self.displayView.layer?.addSublayer(layerTop)
        layerTop.backgroundColor = CGColor.black
        self.layerTop = layerTop
        self.halfW1 = layerTop.halfW
        self.layerTop.borderColor = self.displayView.layer?.borderColor
        self.layerTop.borderWidth = 1
        
        if let image = self.img {
            var imageRect = CGRect(origin: CGPoint.zero, size: image.size)
            
            let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
            if let imageRef = imageRef {
                self.bitImg = NSBitmapImageRep(cgImage: imageRef)
                self.layerTop.image = imageRef
                self.layerTop.setNeedsDisplay()
            }
        }
        
        let layerPoint = CALayer()
        let w = CGFloat(5)
        var x = layerTop.frame.width * 0.5 - w * 0.5
        layerPoint.frame = CGRect(x: x, y: x, width: w, height: w)
        layerPoint.backgroundColor = CGColor.black
        layerPoint.borderWidth = 1
        layerPoint.borderColor = CGColor.white
        layerPoint.cornerRadius = w * 0.5
        layerTop.addSublayer(layerPoint)
        
        x = layerTop.frame.width * 0.5
        hexLayer.frame = CGRect(x: 0, y: 0, width: x + x, height: 25)
        hexLayer.fontSize = 14
        hexLayer.backgroundColor = CGColor(red: 0, green: 0, blue: 0, alpha: 0.2)
        hexLayer.alignmentMode = .center
        layerTop.addSublayer(hexLayer)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(1)) {
            wself?.showTipWithPosition(NSEvent.mouseLocation)
        }
        
        NSCursor.hide()
    }
    
    override func viewDidAppear() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(1)) {
            NSApp.presentationOptions = [.disableAppleMenu]
        }
    }
    
    
    private func showTipWithPosition(_ pos: NSPoint){
        var point = NSPoint(x: pos.x, y: pos.y)
        getColor(point: NSPoint(x: point.x, y: self.view.frame.height - point.y))
        
        point.y -= self.halfW
        point.x -= self.halfW
        
        self.displayView.frame = CGRect(origin: point, size: self.displayView.frame.size)
    }
    
    private func closeTip(){
        self.view.window?.close()
        let ad = NSApplication.shared.delegate as! AppDelegate
        ad.mainWindow?.showWindow(nil)
        
        self.didPickColor?(self.displayView.layer?.backgroundColor)
    }
    
    private func getColor(point: NSPoint){
        if let image = self.img {
            let sh = image.size.height / self.imgView.frame.height
            let sw = image.size.width / self.imgView.frame.width
            var p = NSPoint(x: point.x * sw, y: point.y * sh)
            self.displayView.layer?.backgroundColor = self.bitImg?.colorAt(x: Int(p.x), y: Int(p.y))?.cgColor
            
            if let comp = self.displayView.layer?.backgroundColor?.components {
                self.hexLayer.string = String(format: "%02x%02x%02x", Int(comp[0] * CGFloat(255)), Int(comp[1] * CGFloat(255)), Int(comp[2] * CGFloat(255)))
            }
            
            p = NSPoint(x: p.x - halfW1, y: p.y - halfW1)
            self.layerTop.point = p
            self.layerTop.setNeedsDisplay()
        }
    }
    
    
    deinit {
        NSApp.presentationOptions = [.disableAppleMenu]
        NSCursor.unhide()
    }
    
}
